#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_adc.h"

void ADCInit(void)
{
    ADC_InitTypeDef adcInitStruct;
    ADC_CommonInitTypeDef adcCommonInitStruct;
    GPIO_InitTypeDef gpioInitStruct;

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);

    gpioInitStruct.GPIO_Pin = GPIO_Pin_1;
    gpioInitStruct.GPIO_Mode = GPIO_Mode_AN;
    GPIO_Init(GPIOA, &gpioInitStruct);

    adcCommonInitStruct.ADC_Mode = ADC_Mode_Independent;
    adcCommonInitStruct.ADC_Prescaler = ADC_Prescaler_Div6;
    adcCommonInitStruct.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
    adcCommonInitStruct.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
    ADC_CommonInit(&adcCommonInitStruct);

    adcInitStruct.ADC_Resolution = ADC_Resolution_12b;
    adcInitStruct.ADC_ScanConvMode = DISABLE;
    adcInitStruct.ADC_ContinuousConvMode = DISABLE;
    adcInitStruct.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
//    adcInitStruct.ADC_ExternalTrigConv = ADC_ExternalTrigConv_Ext_IT11;
    adcInitStruct.ADC_DataAlign = ADC_DataAlign_Right;
    adcInitStruct.ADC_NbrOfConversion = 1;
    ADC_Init(ADC1, &adcInitStruct);

    ADC_Cmd(ADC1, ENABLE);
}

u16 ADCRead(void)
{
    ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_3Cycles);
    ADC_SoftwareStartConv(ADC1);
    while (ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
    return ADC_GetConversionValue(ADC1);
}
